<template>
  <a-form
      id="components-form-demo-normal-login"
      :form="form"
      class="login-form"
      @submit.prevent="handleSubmit"
  >
    <a-form-item>
      <a-input
          v-decorator="[
          'userName',
          { rules: [{ required: true, message: 'Please input your username!' }] },
        ]"
          placeholder="Username"
      >
        <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-input
          v-decorator="[
          'password',
          { rules: [{ required: true, message: 'Please input your Password!' }] },
        ]"
          type="password"
          placeholder="Password"
      >
        <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-checkbox
          v-decorator="[
          'remember',
          {
            valuePropName: 'checked',
            initialValue: true,
          },
        ]"
      >
        Remember me
      </a-checkbox>
      <a class="login-form-forgot" href="">
        Forgot password
      </a>
      <a-button type="primary" html-type="submit" class="login-form-button">
        Log in
      </a-button>
      Or
      <a href="#" @click="showRegisterPage">
        register now!
      </a>
    </a-form-item>
  </a-form>
</template>

<script>
import {login} from "@/request/api";
export default {
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'normal_login' });
  },
  methods: {
    showRegisterPage(){
      this.$emit("toRegister")
    },
    handleSubmit(e) {
      // e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          // values：{userName,password}
          login({username: values.userName,password: values.password}).then(res=>{

            if (res.code === 0){

              this.$store.commit('rememberUserInfo',res.data)
              this.$store.commit('rememberToken',res.msg)

              localStorage.setItem("userName",res.data.username)
              localStorage.setItem("token",res.msg)

              this.$emit("isLogin",true)

            }else{
              this.$message.error('login error!! checked input');
            }

          })
          console.log('Received values of form: ', values);
        }
      });
    },
  },
};
</script>
<style>
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
</style>